package com.zwh.aop;

import org.apache.catalina.connector.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 项目启动类
 * 继承SpringBootServletInitializer类，让项目支持springboot项目打包成war包在tomcat下启动
 * springboot默认只能在tomcat7及以上才可以正常运行
 * exclude = {org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration.class}
 * @author zhangwenhe
 */
@SpringBootApplication
public class Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        this.setRegisterErrorPageFilter(false); // 错误页面有容器来处理，而不是SpringBoot
        return builder.sources(Application.class);
    }

    @Bean
    public GracefulShutdownTomcat gracefulShutdownTomcat(){
        return new GracefulShutdownTomcat();
    }

    @Bean
    public ConfigurableServletWebServerFactory configurableServletWebServerFactory(){
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addConnectorCustomizers(gracefulShutdownTomcat());
        return tomcat;
    }

    /**
     * tomcat优雅关闭
     */
    private static class GracefulShutdownTomcat implements TomcatConnectorCustomizer, ApplicationListener<ContextClosedEvent> {
        private final Logger log = LoggerFactory.getLogger(GracefulShutdownTomcat.class);
        private final int waitTime = 30;
        private volatile Connector connector;

        @Override
        public void customize(Connector connector) {
            this.connector = connector;
        }

        /**
         * 监听 停止操作kill -15
         */
        @Override
        public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
            long startTime = System.currentTimeMillis();
            log.info("接收到 ContextClosedEvent 关闭事件");
            //tomcat暂停对外服务
            connector.pause();
            //获取tomcat线程池
            Executor executor = connector.getProtocolHandler().getExecutor();
            if (executor instanceof ThreadPoolExecutor) {
                try {
                    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
                    //线程池优雅停止(不接收新的请求，等待任务运行完成后关闭线程池)
                    threadPoolExecutor.shutdown();
                    //堵塞等待一定时间，指定时间内关闭成功则返回true，解除堵塞；否则fasle
                    if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) {
                        //超时强制关闭
                        threadPoolExecutor.shutdownNow();
                    }
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }

    }
}
